import router from '@/router/index'
import store from '@/store'
import asyncRoutes from '@/router/asyncRoutes'

const whiteList = ['/login', '/404']

// 获取一级权限标识
function getFirstRoutePermission (permission) {
  const firstPermArr = permission.map(item => {
    return item.split(':')[0]
  })
  // console.log(Array.from(new Set(firstPermArr)))
  // 去重
  // Set 不能存重复的数据,不是一个真实的数组
  return Array.from(new Set(firstPermArr))
}
// 获取二级权限标识
function getSecondRoutePermission (permission) {
  const secondPermArr = permission.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return Array.from(new Set(secondPermArr))
}

// 根据一级和二级权限标识筛选出对应的可展示的动态路由
function getRoutes (firstPermission, secondPermission, asyncRoutes) {
  // 判断当前登陆的人是不是管理员，如果是管理员就不进行筛选
  if (firstPermission.includes('*')) {
    return asyncRoutes
  }
  const firstRoutes = asyncRoutes.filter(item =>
    firstPermission.includes(item.permission)
  )
  // console.log(firstRoutes)

  const routes = firstRoutes.map(item => {
    // console.log(item)
    return {
      ...item,
      children: item.children.filter(child =>
        secondPermission.includes(child.permission)
      )
    }
  })
  // console.log(routes)
  return routes
}

router.beforeEach(async (to, from, next) => {
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 1.拿到用户权限信息
      const permission = await store.dispatch('menu/getUserPermission')
      // console.log(permission)
      // 2.根据权限标识，筛选出对应的一级路由的标识
      const firstPermission = getFirstRoutePermission(permission)
      // 3.筛选出二级路由的标识
      const secondPermission = getSecondRoutePermission(permission)
      // 4.根据一级权限和二级权限标识和动态路由进行筛选
      const routes = getRoutes(firstPermission, secondPermission, asyncRoutes)
      // console.log(routes)
      // 5.把筛选后的路由展示到左侧
      routes.forEach(item => {
        router.addRoute(item)
      })
      // 把筛选后的路由添加到vuex中
      store.commit('menu/setMenuList', routes)
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
